<?php
    /* 
    *接口说明: 获取微信用户userid
    *创建者: 	kai
    *时间:	  	20180311
	*/
	require_once 'dbfunction.php';
	require_once 'config.php';
	$GLOBALS['access_token'] = "";
	$GLOBALS['access_token_time'] = 0;

	// 获取accesstoken
	function getAccessToken(){
		$accessToken = "";
		$urlGetAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". WECHAT_APPID ."&secret=" . WECHAT_APPSECRET;
		$ch = curl_init();
		// 网络通讯获取accesstoken
		curl_setopt($ch, CURLOPT_URL, $urlGetAccessToken);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$accessTokenJson = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($accessTokenJson, true);
		
		// 判断是否有值
		if(array_key_exists("access_token",$arr)){
			$accessToken = $arr["access_token"];
		}
		// 输出返回值
		return $accessToken;
	}

	// 获取accesstoken根据缓存信息
	function getAccessTokenByByCache(){
		// 全局变量为空尝试获取access_token
		$currenttime = strtotime("now");
		if($GLOBALS['access_token'] == "" || ($currenttime - $GLOBALS['access_token_time']) > 7000/* 超过有效时间 */){
			$GLOBALS['access_token'] = getAccessToken();
			$GLOBALS['access_token_time'] =  $currenttime;
		}

		// 输出返回值
		return $GLOBALS['access_token'];
	}

	// 获取需要通知的统计信息列表
	function getNeedNotifyStatRecord(){
		$arrResult = null;
		$conn = null;
		do{
			// 创建连接
			$conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD);
			// 检测连接
			if (!$conn) {
				$arrResult = array(
					"errcode" => 2,
					"info" => "连接mysql数据库失败：". mysqli_connect_errno().":".mysqli_connect_error(),
				);
				break;
			}
			mysqli_set_charset($conn, "utf8");
			// 选择数据库
			if(!mysqli_select_db($conn, DB_DBNAME)){
				$arrResult = array(
					"errcode" => 3,
					"info" => "选择mysql数据库失败：". mysqli_connect_errno().":".mysqli_connect_error(),
				);
				break;
			}

			// 根据shareuniqueid和publisheropenid获取分享的记录
			$QueryOrderStatSql = "select * from orderstat where R1=0";
			$result = mysqli_query($conn, $QueryOrderStatSql);
			if(!$result){
				$arrResult = array(
					"errcode" => 4,
					"info" => "查询orderstat数据库失败。",
				);
				break;
			}

			// 输出所有满足条件的记录
			$arrayRecord = array();
			$index = 0;
			while($row = mysqli_fetch_assoc($result))
			{
				$arrayRecord[] = $row;
			}
	
			// 输出结果
			$arrResult = array(
						"errcode" => 0,
						"record" => json_encode($arrayRecord),
						);
			// 先释放掉资源
			mysqli_free_result($result);
		}while(false);

		// 数据库链接清理
		if($conn){
			mysqli_close($conn);
		}

		return $arrResult;
	}

	// 获取需要通知的统计信息列表
	function getOrderPeopleList($orderstatno){
		$arrResult = null;
		$conn = null;
		do{
			// 创建连接
			$conn = mysqli_connect(DB_HOST, DB_USER, DB_PWD);
			// 检测连接
			if (!$conn) {
				$arrResult = array(
					"errcode" => 2,
					"info" => "连接mysql数据库失败：". mysqli_connect_errno().":".mysqli_connect_error(),
				);
				break;
			}
			mysqli_set_charset($conn, "utf8");
			// 选择数据库
			if(!mysqli_select_db($conn, DB_DBNAME)){
				$arrResult = array(
					"errcode" => 3,
					"info" => "选择mysql数据库失败：". mysqli_connect_errno().":".mysqli_connect_error(),
				);
				break;
			}

			// 根据shareuniqueid和publisheropenid获取分享的记录
			$QuerySql = "select * from orderstatshare where orderstatno=" . $orderstatno;
			$result = mysqli_query($conn, $QuerySql);
			if(!$result){
				$arrResult = array(
					"errcode" => 4,
					"info" => "查询失败:". mysqli_connect_errno().":".mysqli_connect_error(),
					"sql" => $QuerySql,
				);
				break;
			}

			// 输出所有满足条件的记录
			$arrayRecord = array();
			$index = 0;
			while($row = mysqli_fetch_assoc($result))
			{
				$arrayRecord[] = $row;
			}
	
			// 输出结果
			$arrResult = array(
						"errcode" => 0,
						"record" => json_encode($arrayRecord),
						);
			// 先释放掉资源
			mysqli_free_result($result);
		}while(false);

		// 数据库链接清理
		if($conn){
			mysqli_close($conn);
		}

		return $arrResult;
	}

	// 通知用户
	function notifyUser($openid, $formid, $template_id, $key1Value, $key2Value){
		$output = "";
		do{
			$access_token = getAccessTokenByByCache();
			// 判断是否为空
			if($access_token == ""){
				break;
			}
			$arrayKey1 = array(
				"value" => $key1Value, 
          		"color" => "#173177",
			);
			$arrayKey2 = array(
				"value" => $key2Value, 
          		"color" => "#173177",
			);
			$data = array(
				"keyword1" => $arrayKey1,
				"keyword2" => $arrayKey2
			);
			// 填充通知数据
			$post_data = array(
                "touser" => $openid,  
  				"template_id" => $template_id, 
  				"page" => "pages/index/index",          
  				"form_id" => $formid,         
 				"data" => $data,
			);
			// 参数设置中文不转码，解决乱码问题
			$post_data_json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
			
			$urlNotify = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token;
			$ch = curl_init();
			// 发送通知
			curl_setopt($ch, CURLOPT_URL, $urlNotify);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			// 设置post
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_json);
			$output = curl_exec($ch);
			curl_close($ch);
			echo $output;
		}while(false);

		return $output;
	}
?>